<template>
  <div>
    <el-dialog title="分配权限" :visible.sync="dialogFormVisible" @open="findMenuTree" style="height:100%">
        <el-tree
          style="height: 400px; overflow-y: auto"
          ref="tree"
          :data="menuTree"
          show-checkbox
          node-key="menuId"
          default-expand-all
          :default-checked-keys="menuIds"
          :props="{ children: 'children', label: 'name' }">
        </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="update">更 新</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import {menuApi} from "../../../http/modules/menu";
  import {roleApi} from "../../../http/modules/role";
  export default {
    name: "permissionTreeDialog",
    props: {
      menuIds: {
        type: Array,
        default: []
      }
    },
    data() {
      return {
        menuTree: [],
      }
    },
    computed: {
      ...mapState({
        dialogFormVisible: state => state.role.permissionDialogVisible,
        roleId: state => state.role.roleId
      })
    },
    methods: {
      findMenuTree() {
        menuApi.findMenuTree().then(data => {
          this.menuTree = data.data
        }).catch(error => {
          console.log(error)
        })
      },

      cancel() {
        let visible = false
        this.$store.commit('setDialogVisible', {visible})
      },
      update() {
        let checkedMenuIds = this.$refs.tree.getCheckedKeys()
        let halfCheckedMenuIds = this.$refs.tree.getHalfCheckedKeys()
        let menuIds = halfCheckedMenuIds.concat(checkedMenuIds)
        let roleMenu = {
          roleId: this.$store.state.role.roleId,
          menuIds: menuIds
        }
        roleApi.updateRoleMenu(roleMenu).then(res => {
          this.$message.success('更新成功')
        }).catch(error => {
          console.log(error)
          this.$message.error('更新失败')
        })
        this.cancel()
      }
    },
  }
</script>

<style lang="scss" scoped>
</style>
